﻿using System.Windows;
using System.Windows.Controls;

namespace Microsoft.Services.Clab.UI.Mvvmc.Presentation
{
    public class WpfViewHelper : ViewHelper
    {
        public static void InitializeView<TView>(TView view, IViewModel viewModel) where TView : IView
        {
            view.ViewModel = viewModel;

            #region Set ViewModel as DataContext
            {
                var cc = view as ContentControl;
                if (cc != null)
                {
                    var ccContent = cc.Content as FrameworkElement;
                    if (ccContent != null)
                    {
                        ccContent.DataContext = viewModel;
                    }
                }
            }
            #endregion

            #region Initialize mapped ViewModel properties with View property values
            {
#if (!SILVERLIGHT)
                var wpfViewModel = viewModel as WpfViewModelBase;
#else
                var wpfViewModel = viewModel as SilverlightViewModelBase;
#endif
                if (wpfViewModel != null)
                {
                    wpfViewModel.PropertySyncHelper.UpdateAllViewModelProperties(view, wpfViewModel);
                }
            }
            #endregion

            view.State = ViewState.Initialized;
        }

        public static void OnContentChanged<TView>(TView view, object oldContent, object newContent) where TView : IView
        {
            var oldFE = oldContent as FrameworkElement;
            if (oldFE != null)
            {
                oldFE.DataContext = null;
            }

            var newFE = newContent as FrameworkElement;
            if (newFE != null && view.ViewModel != null)
            {
                newFE.DataContext = view.ViewModel;
            }
        }

        public static void UpdatePropertyMapping<TView>(TView view, DependencyProperty property) where TView : IView
        {
#if (!SILVERLIGHT)
            var viewModel = view.ViewModel as WpfViewModelBase;
#else
            var viewModel = view.ViewModel as SilverlightViewModelBase;
#endif
            if (viewModel != null && viewModel.PropertySyncHelper != null)
            {
                viewModel.PropertySyncHelper.UpdateViewModelProperty(view, property, viewModel);
            }
        }
    }
}
